package com.diyunapp.xilinapp.details;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.ParamsBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.FlowRadioGroup;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/22.
 */
public class GoodBuyActivity extends Activity implements View.OnClickListener {

    @Bind(R.id.buy_good_img)
    ImageView buyGoodImg;
    @Bind(R.id.buy_good_description_tv)
    TextView buyGoodDescriptionTv;
    @Bind(R.id.buy_good_price_tv)
    TextView buyGoodPriceTv;
    @Bind(R.id.good_parameters_select_ll)
    LinearLayout goodParametersSelectLl;
    @Bind(R.id.buy_incressnum_bt)
    Button buyIncressnumBt;
    @Bind(R.id.buy_decressnum_bt)
    Button buyDecressnumBt;
    @Bind(R.id.buygood_close_imt)
    ImageButton buygoodCloseImt;
    @Bind(R.id.buy_numset_et)
    EditText buyNumsetEt;

    private String good_Id;
    private String good_Img;
    private String good_Price;
    private String good_Store;
    private String goods_name;

    private String goodParams;
    private String specParams;
    private String paramesNameStr;
    private String paramesValueStr;
    private List<ParamsBean> paramsNameList = new ArrayList<>(); //产品规格分类列表
    private List<ParamsBean>[] paramsValueList;//产品各类规格的值列表
    private List<ParamsBean> goodsValueList = new ArrayList<>();  //本产品对应的参数规格选定值
    private int[] selectedParames;
    private StringBuffer selectedKey = new StringBuffer("");
    private StringBuffer commitParams = new StringBuffer("");

    private View bottome_View;
    private Button buy_bt;
    private LinearLayout add_buycar_ll;
    private static int buyNum = 1;

    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";

    //显示图片的配置
    DisplayImageOptions options;
    private boolean ifgetGoods = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.good_buy_layout);
        ButterKnife.bind(this);
        loginKey = MainActivity.myLogin.getLoginkey();
        good_Id = getIntent().getStringExtra("GoodId");
        good_Img = getIntent().getStringExtra("GoodImg");
        good_Store = getIntent().getStringExtra("GoodStore");
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.order_default) // resource or drawable
                .showImageForEmptyUri(R.drawable.order_default) // resource or drawable
                .showImageOnFail(R.drawable.order_default) // resource or drawable
                .cacheInMemory()
                .cacheOnDisc()
                .build();
        bottome_View = findViewById(R.id.buy_good_bottom_inc);
        buy_bt = (Button) bottome_View.findViewById(R.id.buyatonce_bt);
        buy_bt.setOnClickListener(this);
        add_buycar_ll = (LinearLayout) bottome_View.findViewById(R.id.addtobuycar_bt_bt);
        add_buycar_ll.setOnClickListener(this);

        buyIncressnumBt.setOnClickListener(this);
        buyDecressnumBt.setOnClickListener(this);
        buygoodCloseImt.setOnClickListener(this);

        buyNumsetEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i("zhangxiaoxidebug","您正在输入购买数量="+s);
                if(!s.toString().isEmpty())
                {
                    buyNum = FormatConfirm.stringToInt(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        getGoodsDetails();
    }

    @Override
    public void onClick(View v) {
        if ((!ifgetGoods) && (v.getId() != R.id.buygood_close_imt)) {
            return;
        }
        switch (v.getId()) {
            case R.id.buygood_close_imt:
                finish();
                break;
            case R.id.buy_incressnum_bt:
                changeNum(true);
                break;
            case R.id.buy_decressnum_bt:
                changeNum(false);
                break;
            case R.id.buyatonce_bt:
                gotoConfirmOrder();
                break;
            case R.id.addtobuycar_bt_bt:
                addToBuyCar();
                break;
            default:
                break;
        }
    }

    private void gotoConfirmOrder() {
        if(paramsNameList.size()>0)
        {
            commitParams.append(paramsValueList[0].get(selectedParames[0]).getParamsKey());
            for(int i=1;i<paramsNameList.size();i++)
            {
                commitParams.append("  ");
                commitParams.append(paramsValueList[i].get(selectedParames[i]).getParamsKey());
            }
        }
        Intent buyInt = new Intent(this, OrderConfirmActivity.class);
        buyInt.putExtra("CardId", good_Id+"|"+buyNum);
        buyInt.putExtra("IfCart", "0");
        startActivityForResult(buyInt,1);
    }

    private void changeNum(boolean b) {

        if (b)
        {
            buyNum++;
        }
        else
        {
            if(buyNum>1)
            {
                buyNum--;
            }
            else
            {
                Toast.makeText(getApplicationContext(),"至少购买一件商品",Toast.LENGTH_LONG).show();
            }
        }
        buyNumsetEt.setText(String.valueOf(buyNum));
    }

    private void addParameters() {
        final int paramsNum = paramsNameList.size();
        goodsValueList = FormatConfirm.getParameters(goodParams);
        selectedParames = new int[paramsNum];
        for (int i = 0; i < paramsNameList.size(); i++) {
            TextView parameters1_tv = new TextView(this);
            parameters1_tv.setText(paramsNameList.get(i).getParamsKey());
            parameters1_tv.setTextColor(0xff4d4d4d);
            parameters1_tv.setTextSize(13);
            parameters1_tv.setPadding(0, 0, 0, 15);
            parameters1_tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            Log.i("zhangxiaoxidebug","add textview i="+i);
            goodParametersSelectLl.addView(parameters1_tv);

            FlowRadioGroup tempRG = new FlowRadioGroup(this);
            String currentKey = goodsValueList.get(i).getParamsId();

            //为每项规格paramsRG[i]添加radiobutton 选项
            int[] radiobuttonId = new int[paramsValueList[i].size()];
            int selectedId = 0;
            for (int j = 0; j < paramsValueList[i].size(); j++) {
                RadioButton tempButton = new RadioButton(this);
                tempButton.setBackgroundResource(R.drawable.params_radiobuttion_background_selector);   // 设置RadioButton的背景图片
                tempButton.setButtonDrawable(R.drawable.params_radiobuttion_background_selector);           // 设置按钮的样式
                tempButton.setButtonDrawable(android.R.color.transparent);
                tempButton.setPadding(15,5,15,5);// 设置文字距离按钮四周的距离
                tempButton.setText(paramsValueList[i].get(j).getParamsKey());
                tempButton.setTextColor(getResources().getColorStateList(R.color.params_radiobuttion_text_selector));
                tempButton.setTextSize(13);

                Log.i("zhangxiaoxidebug","add tempButton j="+j);
                tempRG.addView(tempButton);

                if(paramsValueList[i].get(j).getParamsId().equals(currentKey))
                {
                    //保存当前规格选中的参数值
                    selectedParames[i]=j;
                    selectedId =  tempButton.getId();
                    Log.i("zhangxiaoxidebug","selectedId = "+ selectedId);
                }
                radiobuttonId[j] = tempButton.getId();
            }

            final int[] radioId=radiobuttonId;
            final int tempint = i;
            tempRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    Log.i("zhangxiaoxidebug","checkedId = "+ checkedId);
                    for(int positon =0;;positon++)
                    {
                        if(radioId[positon] ==  checkedId)
                        {
                            selectedParames[tempint] = positon;
                            break;
                        }
                    }

                    //有任何一项参数修改后，都要重新组查询下商品id
                    selectedKey.delete(0,selectedKey.length());
                    for(int m=0;m<paramsNum;m++)
                    {
                        Log.i("zhangxiaoxidebug","m = "+m);
                        if(m>0)
                        {
                            selectedKey.append("|");
                        }
                        selectedKey.append(paramsValueList[m].get(selectedParames[m]).getParamsId());
                    }

                    Log.i("zhangxiaoxidebug","selectedKey = "+selectedKey.toString());
                    //生成key之后
                    try {
                        JSONObject spec_list = new JSONObject(specParams);
                        good_Id =spec_list.getString(selectedKey.toString());
                        Log.i("zhangxiaoxidebug","good_Id = "+good_Id);
                        freshGoodsDetails();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            RadioButton selectedButton = (RadioButton)tempRG.getChildAt(selectedParames[i]);
            selectedButton.setChecked(true);
            Log.i("zhangxiaoxidebug","add tempRG i="+i);
            goodParametersSelectLl.addView(tempRG);
        }
    }

    public void getValueParameters() {
        try {
            Log.i("zhangxiaoxidebug", "paramesValueStr=" + paramesValueStr);
            paramsValueList = new ArrayList[paramsNameList.size()];
            JSONObject jsobjectValue = new JSONObject(paramesValueStr);
            for (int i = 0; i < paramsNameList.size(); i++) {
                String value = jsobjectValue.getString(paramsNameList.get(i).getParamsId());
                paramsValueList[i] = FormatConfirm.getParameters(value);
                Log.i("zhangxiaoxidebug", "paramsValueList i=" + i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        addParameters();
    }

    private void getGoodsDetails() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=goods_detail&goods_id=" + good_Id;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {
                        ifgetGoods = false;
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "detail_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            JSONObject jsObjectGoodsinfo = jsObjectDatas.getJSONObject("goods_info");
                            goods_name = jsObjectGoodsinfo.getString("goods_name");
                            buyGoodDescriptionTv.setText(goods_name);
                            //考虑有优惠活动的商品
                            good_Price= jsObjectGoodsinfo.getString("goods_price");
                            String PriceText="";
                            if (jsObjectGoodsinfo.has("promotion_price")) {
                                String promotion_price = jsObjectGoodsinfo.getString("promotion_price");
                                PriceText = PriceText+"￥" + promotion_price;
                                if(jsObjectGoodsinfo.has("title"))
                                {
                                    PriceText = PriceText+"("+jsObjectGoodsinfo.getString("title");
                                    if(jsObjectGoodsinfo.has("upper_limit"))
                                    {
                                        int upper_limit = FormatConfirm.stringToInt(jsObjectGoodsinfo.getString("upper_limit"));
                                        if(upper_limit>0)
                                        {
                                            PriceText = PriceText + "，限购" + upper_limit+"件";
                                        }
                                    }
                                    PriceText = PriceText+")";
                                }

                                PriceText = PriceText + "  (原售价￥"+good_Price+")";

                                SpannableString goodPriceSp = new SpannableString(PriceText);
                                int indexTitle = PriceText.indexOf("(");
                                int indexOragin = PriceText.indexOf("  (原售价");

                                //设置字体大小
                                goodPriceSp.setSpan(new AbsoluteSizeSpan(12, true), indexTitle,PriceText.length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                                //设置字体颜色
                                goodPriceSp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey_old_price)), indexOragin, PriceText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                buyGoodPriceTv.setText(goodPriceSp);
                            }
                            else
                            {
                                buyGoodPriceTv.setText("￥" + good_Price);
                            }
                            //-------
                            good_Img = jsObjectDatas.getString("spec_image");
                            ImageLoader.getInstance().displayImage(good_Img, buyGoodImg, options);
                            paramesNameStr = jsObjectGoodsinfo.getString("spec_name");
                            if (paramesNameStr == null || paramesNameStr.isEmpty() || paramesNameStr.equals("null")) {
                                return 1;
                            }
                            paramsNameList = FormatConfirm.getParameters(paramesNameStr);
                            if (paramsNameList.size() > 0) {
                                paramesValueStr = jsObjectGoodsinfo.getString("spec_value");
                                goodParams = jsObjectGoodsinfo.getString("goods_spec");
                                Log.i("zhangxiaoxidebug","goodParams = "+goodParams);
                                specParams = jsObjectDatas.getString("spec_list");
                                getValueParameters();
                            }
                            ifgetGoods = true;
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void freshGoodsDetails() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=goods_detail&goods_id=" + good_Id;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {
                        ifgetGoods = false;
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "detail_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            JSONObject jsObjectGoodsinfo = jsObjectDatas.getJSONObject("goods_info");
                            goods_name = jsObjectGoodsinfo.getString("goods_name");
                            buyGoodDescriptionTv.setText(goods_name);
                            //考虑有优惠活动的商品
                            good_Price= jsObjectGoodsinfo.getString("goods_price");
                            String PriceText="";
                            if (jsObjectGoodsinfo.has("promotion_price")) {
                                String promotion_price = jsObjectGoodsinfo.getString("promotion_price");
                                PriceText = PriceText+"￥" + promotion_price;
                                if(jsObjectGoodsinfo.has("title"))
                                {
                                    PriceText = PriceText+"("+jsObjectGoodsinfo.getString("title");
                                    if(jsObjectGoodsinfo.has("upper_limit"))
                                    {
                                        int upper_limit = FormatConfirm.stringToInt(jsObjectGoodsinfo.getString("upper_limit"));
                                        if(upper_limit>0)
                                        {
                                            PriceText = PriceText + "，限购" + upper_limit+"件";
                                        }
                                    }
                                    PriceText = PriceText+")";
                                }

                                PriceText = PriceText + "  (原售价￥"+good_Price+")";

                                SpannableString goodPriceSp = new SpannableString(PriceText);
                                int indexTitle = PriceText.indexOf("(");
                                int indexOragin = PriceText.indexOf("  (原售价");

                                //设置字体大小
                                goodPriceSp.setSpan(new AbsoluteSizeSpan(12, true), indexTitle,PriceText.length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                                //设置字体颜色
                                goodPriceSp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey_old_price)), indexOragin, PriceText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                buyGoodPriceTv.setText(goodPriceSp);
                            }
                            else
                            {
                                buyGoodPriceTv.setText("￥" + good_Price);
                            }
                            //---------
                            good_Img = jsObjectDatas.getString("goods_image");
                            ImageLoader.getInstance().displayImage(good_Img, buyGoodImg, options);
                            ifgetGoods  = true;
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void addToBuyCar() {

        String url = "http://www.xilingou.com/mobile/index.php?act=member_cart&op=cart_add";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("goods_id", good_Id);
        params.addBodyParameter("quantity", String.valueOf(buyNum));

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "购物车添加失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            }
                            {
                                String datas = jsObjectCode.getString("datas");
                                if (datas.equals("1")) {
                                    Toast.makeText(getApplicationContext(), "购物车添加成功！", Toast.LENGTH_SHORT).show();
                                }
                                else {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "购物车添加失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //从店铺返回时刷新

        if(requestCode == 1 && resultCode == 1)
        {
            //如果提交订单页面是因为订单提交成功而返回的时，则将此购买页面也关闭掉
            finish();
        }

        super.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    protected void onDestroy() {
        buyNum = 1;
        super.onDestroy();
    }
}
